<script setup>
import { ref, onMounted, nextTick } from 'vue';
import request from '@/utils/request';
import moment from'moment';

// 响应式数据
const loading = ref(true);
const ruleForm = ref({});
const dialogVisible = ref(false);
const search = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
const vis = ref(false);
const detail = ref({});
const rules = {
    appointmentTime: [
        { required: true, message: '请选择预约体检时间', trigger: 'blur' }
    ],
    mealId: [
        { required: true, message: '请选择体检套餐', trigger: 'blur' }
    ]
};
const multipleSelection = ref([]);
const checkItemsData = ref([]);
const mealOptions = ref([]);
const loginUser = ref({});
const groupsInMeal = ref([]);
const checkGroupsData = ref([]);

// 获取套餐列表
const getMealList = () => {
    request.post("/checkSetMeal/getMealList", {}).then((res) => {
        res.data.forEach((element) => {
            element.label = element.name;
            element.value = element.id;
        });
        mealOptions.value = res.data;
        console.log("新的下拉选信息：：", mealOptions.value);
    });
};

// 加载数据
const load = () => {
    loading.value = true;
    request.get("/appointment", {
        params: {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            search: search.value,
            userId: loginUser.value.id
        }
    }).then((res) => {
        loading.value = false;
        tableData.value = res.data.records;
        total.value = res.data.total;
    });
};

// 文件上传成功处理
const filesUploadSuccess = (res) => {
    console.log(res);
    ruleForm.value.cover = res.data;
};

// 添加操作
const add = () => {
    dialogVisible.value = true;
    ruleForm.value = {};
};

// 保存操作
const save = (formName) => {
    const form = getCurrentInstance().proxy.$refs[formName];
    form.validate((valid) => {
        if (valid) {
            if (ruleForm.value.id) {
                mealOptions.value.forEach((element) => {
                    if (ruleForm.value.mealId === element.id) {
                        ruleForm.value.mealName = element.name;
                    }
                });
                console.log(ruleForm.value);
                if (ruleForm.value.mealId === 0) {
                    console.log('你选择的套餐是自定义');
                    console.log('你选择的检查组有', multipleSelection.value);
                    const selectData = JSON.parse(JSON.stringify(multipleSelection.value));
                    const groupIds = selectData.map((element) => element.id);
                    ruleForm.value.groupIds = groupIds.join(',');
                    console.log('要提交的检查组id有', ruleForm.value.groupIds);
                }
                request.put("/appointment", ruleForm.value).then((res) => {
                    if (res.code === '0') {
                        app.config.globalProperties.$message({
                            type: "success",
                            message: "更新成功"
                        });
                    } else {
                        app.config.globalProperties.$message({
                            type: "error",
                            message: res.msg
                        });
                    }
                    load();
                    dialogVisible.value = false;
                });
            } else {
                const userStr = sessionStorage.getItem("user") || "{}";
                const user = JSON.parse(userStr);
                mealOptions.value.forEach((element) => {
                    if (ruleForm.value.mealId === element.id) {
                        ruleForm.value.mealName = element.name;
                    }
                });
                ruleForm.value.createPeople = user.nickName;
                ruleForm.value.appointmentPeople = user.nickName;
                ruleForm.value.appointmentTime = moment(ruleForm.value.appointmentTime).format('YYYY-MM-DD HH:mm:ss');
                ruleForm.value.appointmentPeopleId = user.id;
                if (ruleForm.value.mealId === 0) {
                    console.log('你选择的套餐是自定义');
                    console.log('你选择的检查组有', multipleSelection.value);
                    const selectData = JSON.parse(JSON.stringify(multipleSelection.value));
                    const groupIds = selectData.map((element) => element.id);
                    ruleForm.value.groupIds = groupIds.join(',');
                    console.log('要提交的检查组id有', ruleForm.value.groupIds);
                }
                console.log("this.ruleForm::", ruleForm.value);
                request.post("/appointment", ruleForm.value).then((res) => {
                    if (res.code === '0') {
                        app.config.globalProperties.$message({
                            type: "success",
                            message: "新增成功"
                        });
                    } else {
                        app.config.globalProperties.$message({
                            type: "error",
                            message: res.msg
                        });
                    }
                    load();
                    dialogVisible.value = false;
                });
            }
        } else {
            console.log('error submit!!');
            return false;
        }
    });
};

// 编辑操作
const handleEdit = (row) => {
    const now = moment(moment().format('YYYY-MM-DD'));
    if (moment(row.appointmentTime) < now) {
        app.config.globalProperties.$message({
            type: "warning",
            message: "体检时间已过，不可以编辑了呦~~~"
        });
        return;
    }
    dialogVisible.value = true;
    onMealChange();
    ruleForm.value = JSON.parse(JSON.stringify(row));
    if (ruleForm.value.mealId === 0) {
        console.log('勾选回显');
        const formData = JSON.parse(JSON.stringify(row));
        nextTick(() => {
            if (formData.groupIds) {
                const ids = formData.groupIds.split(',');
                console.log("ids：：", ids);
                groupsInMeal.value.forEach((element, idx) => {
                    ids.forEach((id) => {
                        if (id === element.id) {
                            console.log('初始化选中', element);
                            const multipleTable = getCurrentInstance().proxy.$refs.multipleTable;
                            multipleTable.toggleRowSelection(groupsInMeal.value[idx], true);
                        }
                    });
                });
            }
        });
    }
};

// 删除操作
const handleDelete = (row) => {
    const now = moment(moment().format('YYYY-MM-DD'));
    if (moment(row.appointmentTime) < now) {
        app.config.globalProperties.$message({
            type: "warning",
            message: "体检时间已过，不可以取消了呦~~~"
        });
        return;
    }
    row.isDel = 1;
    request.put("/appointment", row).then((res) => {
        if (res.code === '0') {
            app.config.globalProperties.$message({
                type: "success",
                message: "删除成功"
            });
        } else {
            app.config.globalProperties.$message({
                type: "error",
                message: res.msg
            });
        }
        load();
    });
};

// 每页个数改变
const handleSizeChange = (newPageSize) => {
    pageSize.value = newPageSize;
    load();
};

// 当前页码改变
const handleCurrentChange = (newPageNum) => {
    currentPage.value = newPageNum;
    load();
};

// 切换选中状态
const toggleSelection = (rows) => {
    const multipleTable = getCurrentInstance().proxy.$refs.multipleTable;
    if (rows) {
        rows.forEach((row) => {
            multipleTable.toggleRowSelection(row);
        });
    } else {
        multipleTable.clearSelection();
    }
};

// 选中状态改变
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 时间选择改变
const timeChange = () => {
    const now = moment(moment().format('YYYY-MM-DD'));
    if (moment(ruleForm.value.appointmentTime) < now) {
        app.config.globalProperties.$message({ type: "error", message: '预约时间必须是今日或将来的日期' });
        ruleForm.value.appointmentTime = null;
        return;
    }
    const params = { appointmentDay: moment(ruleForm.value.appointmentTime).format('YYYY-MM-DD') };
    console.log("校验时的时间参数：：", params);
    request.post("/appointment/validateCount", params).then((res) => {
        if (res.code === 0) {
            app.config.globalProperties.$message({ type: "success", message: res.data });
        } else {
            ruleForm.value.appointmentTime = null;
            app.config.globalProperties.$message({ type: "error", message: res.msg });
        }
    });
};

// 套餐选择改变
const onMealChange = () => {
    if (ruleForm.value.mealId === 0) {
        console.log('你选择了自定义套餐');
        request.post("/checkGroup/getCheckGroupList", ruleForm.value).then((res) => {
            checkGroupsData.value = res.data;
            groupsInMeal.value = checkGroupsData.value;
            console.log('所有的检查组信息', checkGroupsData.value);
        });
        return;
    }
    console.log('你选择了套餐,套餐id为', ruleForm.value.mealId);
    request.get('/checkGroup/byMealId', {
        params: {
            mealId: ruleForm.value.mealId
        }
    }).then((res) => {
        if (res.code === '-1') {
            app.config.globalProperties.$message({
                type: "warning",
                message: res.msg
            });
            return;
        }
        groupsInMeal.value = res.data;
    });
};

onMounted(() => {
    const userStr = sessionStorage.getItem("user") || "{}";
    loginUser.value = JSON.parse(userStr);
    load();
    getMealList();
});
</script>

<template>
  <div style="padding: 10px">
    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" placeholder="请输入关键字" style="width: 20%" clearable></el-input>
      <el-button style="margin-left: 5px" @click="load">查询</el-button>
      <el-button type="primary" @click="add">我要预约</el-button>
    </div>
    <el-table v-loading="loading" :data="tableData" border stripe style="width: 100%">

      <template #empty>
        <el-empty description="您还没有预约呦呦~~~" />
      </template>

      <el-table-column type="index" label="序号" sortable align="center">
      </el-table-column>
      <el-table-column prop="appointmentPeople" label="预约人" align="center">
      </el-table-column>
      <el-table-column prop="appointmentTime" label="预约时间" align="center">
      </el-table-column>
      <el-table-column prop="mealName" label="所选套餐" align="center">
      </el-table-column>
      <el-table-column prop="remark" label="说明" align="center">
      </el-table-column>

      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button size="mini" type="danger">取消</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="预约信息" v-model="dialogVisible" style="width: 50%; margin: 10% auto 50px;">

      <el-form :model="ruleForm" label-width="120px" :rules="rules" ref="ruleForm">
        <el-form-item label="预约体检时间" prop="appointmentTime">
          <el-date-picker v-model="ruleForm.appointmentTime" type="date" placeholder="请选择预约体检时间" @change="timeChange" />
        </el-form-item>
        <el-form-item label="体检套餐" prop="mealId">
          <el-select v-model="ruleForm.mealId" clearable placeholder="请选择体检套餐" @change="onMealChange">
            <el-option v-for="item in mealOptions" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="检查项目有:">
          <el-table 
          ref="multipleTable"
          :data="groupsInMeal" 
          style="width: 100%" 
          @selection-change="handleSelectionChange">
            <template #empty>
              <el-empty description="你还没有选择套餐呦~~" :image-size="80" />
            </template>
            <el-table-column v-if="ruleForm.mealId === 0" type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column prop="name" label="检查组" width="180" />
            <el-table-column prop="remark" label="说明" width="180" />
          </el-table>
        </el-form-item>

        <el-form-item label="说明">
          <el-input type="textarea" :rows="2" placeholder="请输入补充信息" v-model="ruleForm.remark"></el-input>
        </el-form-item>
      </el-form>


      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="save('ruleForm')">确 定</el-button>
        </span>
      </template>
    </el-dialog>



  </div>
</template>
